package security.filters;

import framework.security.FunctionPermission;
import lombok.Getter;

/**
 * 功能权限处理器
 */
public class FunctionPermissionHandler {

    private String[] permissionArray;
    @Getter
    private final FunctionPermission functionPermission;

    public FunctionPermissionHandler(FunctionPermission functionPermission) {
        this.functionPermission = functionPermission;
        this.splitPermissionArray(functionPermission.getPermission());
    }

    /**
     * 指定该功能是否包含该权限
     *
     * @param permission
     * @return
     */
    public boolean hasPermission(String permission) {
        if (permission == null)
            return false;
        if ("".equals(permission))
            return false;
        String[] arr = this.permissionArray;
        if (arr == null) {
            return permission.equals(functionPermission.getPermission());
        }
        if (arr.length == 1) {
            return permission.equals(functionPermission.getPermission());
        }
        //多权限匹配
        for (String s : arr) {
            if (permission.equals(s)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 将权限拆分为权限集合
     *
     * @param permission
     */
    private void splitPermissionArray(String permission) {
        if (permission == null) {
            this.permissionArray = null;
        } else {
            this.permissionArray = permission.split(",");
        }
    }
}
